<template>
  <div>
    <!-- 列表渲染 -->
    <div class="container">
      <el-card>
        <el-form :inline="true" class="demo-form-inline" style="height: 50px">
          <el-form-item label="关键字" style="marginleft: 30px">
            <el-input
              placeholder="根据文章标题搜索"
              size="small"
              v-model="params.keyword"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" style="marginleft: 40px">
            <el-select placeholder="请选择" size="small" v-model="params.state">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click="clear">清除</el-button>
            <el-button type="primary" size="small" @click="search"
              >搜索</el-button
            >
            <el-button
              type="success"
              icon="el-icon-edit"
              size="small"
              class="addskill"
              @click="addArticle"
              >新增技巧</el-button
            >
          </el-form-item>
        </el-form>
        <el-alert type="info" :closable="false">
          <i class="el-icon-info"></i>
          <span class="alert">数据一共 {{ total }} 条</span>
        </el-alert>

        <!-- 表单列表 -->
        <el-table
          element-loading-text=""
          fit
          highlight-current-row
          style="width: 100%"
          :data="list"
        >
          <el-table-column width="60" label="序号" type="index" />

          <el-table-column width="400" label="文章标题" prop="title">
            <template #default="{ row }">
              {{ row.title }}
              <el-link
                icon="el-icon-film"
                v-show="row.videoURL"
                :style="{ color: 'blue', fontSize: '18px' }"
                @click="showVideo(row.videoURL)"
              ></el-link>
            </template>
          </el-table-column>
          <el-table-column label="阅读数" prop="visits" />
          <el-table-column label="录入人" prop="username"> </el-table-column>
          <el-table-column label="录入时间" prop="createTime">
            <template #default="{ row }">
              {{ formatTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="state">
            <template #default="{ row }">
              {{ formatState(row.state) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="preview(row.id)"
                >预览</el-button
              >
              <el-button type="text" size="small" @click="changeStatus(row)">
                {{ row.state ? "禁用" : "启用" }}
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="editArticle(row.id)"
                :disabled="row.state === 1"
                >修改</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="delArticle(row.id)"
                :disabled="row.state === 1"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.page"
          background
          :page-sizes="[5, 10, 20, 50]"
          layout=" prev, pager, next, sizes,jumper"
          :page-size="params.pagesize"
          :total="total"
        >
        </el-pagination>
      </el-card>
    </div>

    <!-- 预览文章弹框 -->
    <el-dialog
      title="预览文章"
      :visible="dialogVisible"
      @close="closeDialog"
      width="58%"
    >
      <div class="title">
        <h2>{{ previewList.title }}</h2>
      </div>
      <div class="time">
        <span>{{ formatTime(previewList.createTime) }}</span>
        <span>超级管理员</span>
        <i class="el-icon-view"></i>
        <span>{{ previewList.visits }}</span>
      </div>
      <div class="content">
        <span v-html="previewList.articleBody"></span>
      </div>
    </el-dialog>
    <!-- 新增/修改文章弹框 -->
    <el-dialog
      :title="addList.id ? '修改文章' : '新增文章'"
      :visible="showDialog"
      @close="turnoff"
      width="56%"
      class="addForm"
    >
      <template #default>
        <!-- 表单 -->
        <el-form
          ref="addForm"
          label-width="80px"
          :model="addList"
          :rules="rules"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input
              v-model="addList.title"
              style="width: 100%"
              placeholder="请输入文章标签"
            />
          </el-form-item>
          <el-form-item label="文章内容" prop="articleBody">
            <!-- 富文本编辑器 -->
            <quill-editor
              v-model="addList.articleBody"
              :options="editorOption"
            ></quill-editor>
          </el-form-item>
          <el-form-item label="视频地址" prop="videoURL">
            <el-input
              style="width: 100%"
              placeholder="请输入视频地址"
              v-model="addList.videoURL"
            />
          </el-form-item>
        </el-form>
      </template>
      <!-- footer插槽 -->
      <template #footer>
        <div class="footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 视频弹框 -->
    <div class="videomasks" v-if="videoState == true">
      <el-button
        icon="el-icon-error"
        circle
        @click="videoState = false"
      ></el-button>
      <!-- 视频：h5的视频播放video -->
      <video
        :src="videoSrc"
        controls="controls"
        autoplay
        width="100%"
        height="100%"
      >
        您的浏览器不支持 video 标签。
      </video>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
// import { videoPlayer } from 'vue-video-player'
import { list, remove, detail, add, update, changeState } from '@/api/hmmm/articles.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  ['blockquote', 'code-block'], // 引用 代码块-----['blockquote', 'code-block']
  ['image', 'link'] // 链接、图片、视频-----['link', 'image', 'video']
]
export default {
  name: 'MyArticles',
  components: {
    quillEditor
    // videoPlayer
  },
  data () {
    return {
      // 视频播放
      // playerOptions: {
      //   controls: false,
      //   playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
      //   autoplay: false, // 如果true,浏览器准备好时开始回放。
      //   muted: false, // 默认情况下将会消除任何音频。
      //   loop: false, // 导致视频一结束就重新开始。
      //   preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
      //   language: 'zh-CN',
      //   aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
      //   fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
      //   sources: [
      //     {
      //       type: '',
      //       src: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-learning-vue/52e63a10-aecd-11ea-b43d-2358b31b6ce6.mp4' // url地址
      //     }
      //   ],
      //   poster: '', // 你的封面地址
      //   notSupportedMessage: '此视频暂无法播放，请稍后再试',
      //   controlBar: {
      //     timeDivider: true,
      //     durationDisplay: true,
      //     remainingTimeDisplay: false,
      //     fullscreenToggle: true // 全屏按钮
      //   }
      // },
      // 富文本编辑器的配置
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions
          }
        }
      },
      // 列表数据
      list: [],
      total: null,
      // 预览数据
      previewList: [],
      // 添加数据
      addList: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      // 验证规则
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      },
      // 总数据数量
      counts: 0,
      params: {
        page: 1,
        pagesize: 10,
        keyword: '',
        state: null
      },
      // 新增弹框
      dialogVisible: false,
      // 预览弹框
      showDialog: false,
      options: [
        {
          id: 0,
          value: '禁用'
        },
        {
          id: 1,
          value: '启用'
        }],
      btnStatus: 0,
      stateData: {
        id: '',
        state: ''
      },
      // 视频弹框
      videoState: false,
      // 视频地址
      videoSrc: ''
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    // 渲染列表
    async getList () {
      const res = await list(this.params)
      this.list = res.data.items
      this.total = res.data.counts
    },
    // 每页几条数据
    // 分页
    handleSizeChange (val) {
      this.params.pagesize = val
      this.params.page = 1
      this.getList()
    },
    handleCurrentChange (val) {
      this.params.page = val
      this.getList()
    },
    // 格式化事件
    formatTime (value) {
      return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    },
    // 枚举
    formatState (value) {
      const Map = {
        1: '已启用',
        0: '已禁用'
      }
      return Map[value]
    },
    // 清除关键字输入框
    clear () {
      this.params.keyword = ''
      this.params.state = null
    },
    // 搜索
    search () {
      this.getList()
    },
    // 删除
    delArticle (id) {
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove({ id })
        this.getList()
        this.$message.success('删除成功')
      }).catch(() => {

      })
    },
    // 预览文章
    async preview (id) {
      this.dialogVisible = true
      const res = await detail({ id })
      this.previewList = res.data
    },
    // 关闭预览弹框
    closeDialog () {
      this.dialogVisible = false
      this.$refs.addForm.resetFields()
    },
    // 新增文章
    addArticle () {
      this.showDialog = true
    },
    // 关闭新增弹框
    turnoff () {
      this.showDialog = false
      this.$refs.addForm.resetFields()
    },
    // 确定添加/修改文章
    confirm (id) {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          if (this.addList.id) {
            await update(this.addList)
          } else {
            await add(this.addList)
          }
          this.$message.success(`${this.addList.id ? '修改文章' : '新增文章'}成功`)
          this.getList()
          this.turnoff()
          this.$refs.addForm.resetFields()
          this.addList = {
            title: '',
            articleBody: '',
            videoURL: ''
          }
        }
      })
    },
    // 取消添加文章
    cancel () {
      this.turnoff()
      this.addList = {
        title: '',
        articleBody: '',
        videoURL: ''
      }
    },
    // 修改文章
    async editArticle (id) {
      this.showDialog = true
      const res = await detail({ id })
      // this.addList.title = data.title
      // this.addList.articleBody = data.articleBody
      // this.addList.videoURL = data.videoURL
      this.addList = res.data
    },
    // 更改状态
    async changeStatus (stateData) {
      stateData.state = stateData.state ? 0 : 1
      await changeState(stateData)
      this.$message.success('操作成功')
    },
    // 播放视频
    showVideo (row) {
      this.videoState = true
      // this.playerOptions.sources[0].src = this.list.videoURL
      this.videoSrc = row
    }

  }
}
</script>

<style scoped lang='less'>
// 富文本编辑器
.el-form-item::v-deep .ql-editor {
  height: 200px;
}
.el-form-item::v-deep .ql-toolbar.ql-snow {
  height: 38px;
  padding: 0px;
  padding-left: 8px;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.addskill {
  margin-left: 410px;
}
.el-dialog {
  padding: 0 20px;
}
.title {
  padding-bottom: 10px;
  h2 {
    margin: 0;
  }
}
.time {
  height: 25px;
  span,
  i {
    margin-left: 10px;
  }
}
.content {
  border-top: 1px dashed #ccc;
  padding: 10px;
  background: #f5f5f5;
}
.footer {
  text-align: right;
}
.addForm {
  padding: 30px 20px;
}
.videomasks {
  width: 800px;
  height: 500px;
  position: fixed;
  left: 400px;
  top: 550px;
  margin-top: -30%;
  z-index: 20;
  /* transform: translate(-50%, -50%); */
}
.videomasks .el-button {
  display: flex;
  background-color: #000000;
  font-size: 30px;
  opacity: 0.6;
  margin: 0 auto;
}
.el-alert {
  height: 35px;
  line-height: 35px;
  margin-bottom: 15px;
  .alert {
    font-size: 13px;
    padding: 0 10px;
  }
  .el-icon-info {
    font-size: 16px;
  }
}
.container {
  padding: 10px;
}
</style>
